<template>
    <div class="dashboard-container">
        <div class="container">
            <div class="tableBar">
                <el-input v-model="queryParamsName" placeholder="请输入员工姓名" style="width: 250px" clearable>
                    <template #prefix>
                        <el-icon style="cursor: pointer" @click="handleQuery">
                            <search />
                        </el-icon>
                    </template>
                </el-input>
                <el-button type="primary" @click="handleAdd"> + 添加员工 </el-button>
            </div>
            <el-table :data="tableData" stripe class="tableBox">
                <el-table-column prop="name" label="员工姓名"></el-table-column>
                <el-table-column prop="username" label="账号"></el-table-column>
                <el-table-column prop="phone" label="手机号"></el-table-column>
                <el-table-column label="账号状态">
                    <template #default="scope">
                        {{ String(scope.row.status) === '0' ? '已禁用' : '正常' }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="160" align="center">
                    <template #default="scope">
                        <el-button size="small" class="editBut" @click="handleUpdate(scope.row)">编辑</el-button>
                        <el-button size="small" class="delBut" @click="HandleStatus(scope.row)" v-if="user === 'admin'">{{ scope.row.status == '1' ? '禁用' : '启用' }}</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination class="pageList" :page-sizes="[10, 20, 30, 40]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total" v-model:current-page.sync="page" @size-change="handleSizeChange" @current-change="handleCurrentChange"></el-pagination>
        </div>

		<el-dialog v-model="open" :title="dialogTitle">
			<el-form ref="formRef" :model="formData" :rules="formRules" :inline="false" label-width="120px" class="demo-formData">
				<el-form-item label="账号:" prop="username">
					<el-input v-model="formData.username" placeholder="请输入账号" maxlength="20"/>
				</el-form-item>
				<el-form-item label="员工姓名:" prop="name">
					<el-input v-model="formData.name" placeholder="请输入员工姓名" maxlength="20" />
				</el-form-item>
				<el-form-item label="手机号:" prop="phone">
					<el-input v-model="formData.phone" placeholder="请输入手机号" maxlength="20" />
				</el-form-item>
				<el-form-item label="性别:" prop="sex">
					<el-radio-group v-model="formData.sex">
						<el-radio label="1">男</el-radio>
						<el-radio label="0">女</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="身份证号:" prop="idNumber">
					<el-input v-model="formData.idNumber" placeholder="请输入身份证号" maxlength="20" />
				</el-form-item>
			</el-form>
			<template #footer>
				<el-button @click="open = false">取消</el-button>
				<el-button type="primary" @click="submitForm()">保存</el-button>
				<!-- <el-button type="primary" class="continue" @click="submitForm(true)">保存并继续添加</el-button> -->
			</template>
		</el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive } from "vue";
// import { Search } from "@element-plus/icons-vue";
import { ElMessageBox,ElMessage } from 'element-plus';
import { getMemberList, getEmployeeById, addEmployee, editEmployee, updateStatusById } from "@/api/member/member";
import { resetForm } from "@/utils/tool";
import { validName, validPhone, validUserName, validID } from '@/utils/validate';
const user = ref("");
const queryParamsName = ref("");
const total = ref(0);
const page = ref(1);
const pageSize = ref(10);
const tableData = ref([]);

const dialogTitle = ref("");
const formRef = ref();
const formRules = reactive({
    //账号
    username: [{ required: true, validator: validUserName, trigger: "blur" }],
    //姓名
    name: [{ required: true, validator: validName, trigger: "blur" }],
    phone: [{ required: true, validator: validPhone, trigger: "blur" }],
    idNumber: [{ required: true, validator: validID, trigger: "blur" }],
});
const formData = ref({
	id: "",
    name: "",
    phone: "",
    sex: "1",
    idNumber: "",
    username: "",
});
const open = ref(false);

/* 查询员工列表 */
const getList = () => {
    const params = {
        page: page.value,
        pageSize: pageSize.value,
        name: queryParamsName.value ? queryParamsName.value : undefined,
    };
    getMemberList(params).then((res) => {
        tableData.value = res.data.records || [];
        total.value = res.data.total;
    });
};

const createdFunc = () => {
    getList();
    // user.value = JSON.parse(localStorage.getItem("userInfo")).username;
    user.value = "admin";
};
createdFunc();

/* 查询按钮 */
const handleQuery = () => {
    page.value = 1;
    getList();
};

/* 添加按钮 */
const handleAdd = () => {
    resetForm(formRef.value);
    dialogTitle.value = "员工添加";
    open.value = true;
};

/* 修改按钮 */
const handleUpdate = (row) => {
    resetForm(formRef.value);
    dialogTitle.value = "员工修改";
    const params = { id: row.id };
    getEmployeeById(params).then((res) => {
        formData.value = res.data;
        
        //保存原来key对应的值
let departmentId= formData.value.updateUser;
//删除key
delete formData.value.updateUser;
//增加key
formData.value.updateuser=departmentId;
    });
    open.value = true;
};

/* 启用、禁用按钮 */
const HandleStatus = (row) => {
    ElMessageBox.confirm("确认调整该账号的状态?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
    }).then(() => {
		const params = {
			id: row.id,
			status: !row.status ? 1 : 0
		}
        updateStatusById(params).then((res) => {
            if(res.code == 1){
            ElMessage({type: 'success', message: "账号状态更改成功！"});
            getList();
        }else{
            ElMessage({type: 'error', message: res.msg});
        }
            
        });
    });
};

/* 提交按钮 */
const submitForm = () => {
    formRef.value.validate((valid) => {
        if (valid) {
            if (formData.value.id == undefined || formData.value.id == "") {
                addEmployee(formData.value).then((res) => {
					ElMessage({ type: 'success', message: '员工信息添加成功！' });
					open.value = false;
					getList();
				})
            } else {
                editEmployee(formData.value).then((res) => {
					ElMessage({type: 'success', message: '员工信息修改成功！'});
					open.value = false;
                    formData.value.id = "";
					getList();
				})
            }
        }
    });
};

/* 页码按钮 */
const handleSizeChange = (val) => {
    pageSize.value = val;
    getList();
};

/* 每页条目数按钮 */
const handleCurrentChange = (val) => {
    page.value = val;
    getList();
};
</script>

<style lang="scss" scoped>
</style>